package com.wechat.service.storage;

import java.io.File;

import com.swak.utils.FileUtils;
import com.swak.utils.StringUtils;
import com.wechat.exception.StorageException;
import com.wechat.service.StorageService;

import lombok.Getter;

/**
 * 使用本地存储
 * 
 * @author 618lf
 */
public class StorageServiceImpl implements StorageService {

	@Getter
	private final File storagePath;

	public StorageServiceImpl(String storagePath) {
		this.storagePath = new File(storagePath);
	}

	private File file(String path) {
		if (StringUtils.isBlank(path)) {
			return null;
		}
		return new File(storagePath, path);
	}

	private File newFile(String path) {
		try {
			// 创建目标文件
			File file = this.file(path);

			// 创建目录
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}

			// 如果文件创建成功
			if (file.createNewFile()) {
				return file;
			}

			// 文件名称 - 扩展名
			String name = FileUtils.getFileName(file.getName());
			String suffix = FileUtils.getFileSuffix(file.getName());

			// 按序号创建文件
			int num = 1;
			while (file.exists()) {
				file = new File(parent, String.format("%s(%s)%s", name, num++, suffix));
			}

			// 创建新文件
			file.createNewFile();

			// 返回创建成功的文件
			return file;
		} catch (Exception e) {
			throw new StorageException("[创建文件]" + path + "异常", e);
		}
	}

	@Override
	public File write(String path, byte[] datas) {
		File file = this.newFile(path);
		FileUtils.write(file, datas);
		return file;
	}

	@Override
	public File writeIfAbsent(String path, byte[] datas) {
		File file = this.file(path);
		if (file.exists()) {
			return file;
		}
		return this.write(path, datas);
	}

	@Override
	public byte[] read(String path) {
		File file = this.file(path);
		return FileUtils.read(file);
	}

	@Override
	public File open(String path) {
		return this.file(path);
	}

	@Override
	public void delete(String path) {
		File file = this.file(path);
		file.delete();
	}
}
